package com.tencent.iov.cowin.befsale.clue.service.clue.impl;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.github.pagehelper.Page;
import com.google.common.collect.Lists;
import com.software.boot.common.entity.Response;
import com.software.boot.common.exception.BusinessException;
import com.software.boot.common.exception.NEError;
import com.software.boot.common.model.dao.PageRequest;
import com.software.boot.common.model.dao.PageResponse;
import com.software.boot.common.util.*;
import com.software.common.config.SearchLocalHeader;
import com.software.common.enums.DeleteEnum;
import com.software.common.enums.SCRMRequestHeaderEnum;
import com.software.common.utils.BasePropertyInjection;
import com.tencent.iov.cowin.befsale.clue.controller.clue.assembler.ClueCustomerCollectAssembler;
import com.tencent.iov.cowin.befsale.clue.controller.clue.vo.request.ClueExpireRequest;
import com.tencent.iov.cowin.befsale.clue.controller.clue.vo.request.QueryClueCustomerCollectAllRequest;
import com.tencent.iov.cowin.befsale.clue.controller.clue.vo.request.UpdateClueIntentionRequest;
import com.tencent.iov.cowin.befsale.clue.controller.clue.vo.response.*;
import com.tencent.iov.cowin.befsale.clue.controller.cus.vo.request.AddClueCustomerFollowRequest;
import com.tencent.iov.cowin.befsale.clue.controller.cus.vo.request.AddCustomerFollowPlanRequest;
import com.tencent.iov.cowin.befsale.clue.controller.cus.vo.request.ClueIntentionGradeDataRequest;
import com.tencent.iov.cowin.befsale.clue.controller.cus.vo.request.UpdateClueCustomerRequest;
import com.tencent.iov.cowin.befsale.clue.dao.http.mdquery.MdQueryClient;
import com.tencent.iov.cowin.befsale.clue.dao.http.tenant.TenantClient;
import com.tencent.iov.cowin.befsale.clue.dao.http.tenant.request.QueryDictionariesRequest;
import com.tencent.iov.cowin.befsale.clue.dao.http.tenant.response.DictionariesResponse;
import com.tencent.iov.cowin.befsale.clue.domain.clue.po.ClueCustomerCollect;
import com.tencent.iov.cowin.befsale.clue.domain.cus.po.CustomerBehavior;
import com.tencent.iov.cowin.befsale.clue.domain.cus.vo.ClueDictionaryMapped;
import com.tencent.iov.cowin.befsale.clue.domain.cus.vo.ClueDictionaryMappedCollect;
import com.tencent.iov.cowin.befsale.clue.repository.clue.ClueCustomerCollectManager;
import com.tencent.iov.cowin.befsale.clue.service.clue.ClueCustomerCollectService;
import com.tencent.iov.cowin.befsale.clue.service.clue.ClueIntentionVehicleService;
import com.tencent.iov.cowin.befsale.clue.service.tenant.DictionaryService;
import com.tencent.iov.cowin.befsale.clue.value.enums.*;
import com.tencent.iov.cowin.befsale.clue.value.utils.CommonUtil;
import com.tencent.iov.cowin.befsale.clue.value.utils.CustomerUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.ibatis.session.RowBounds;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.context.config.annotation.RefreshScope;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.stream.Collectors;

/**
 * @Describe: 线索客户宽表_Service实现层
 * @author: whp
 * @created: 2021-12-23 14:53:39
 * @version: 1.0
 */
@Slf4j
@Service
@RefreshScope
public class ClueCustomerCollectServiceImpl implements ClueCustomerCollectService {

    @Autowired
    private ClueCustomerCollectManager clueCustomerCollectManager;
    @Autowired
    private TenantClient tenantClient;
    @Autowired
    private ClueDictionaryMappedCollect clueDictionaryTypes;
    @Autowired
    private ClueIntentionVehicleService clueIntentionVehicleService;
    @Autowired
    private MdQueryClient mdQueryClient;

    @Autowired
    private DictionaryService dictionaryService;

    @Value("${properties.intention.grade.type:}")
    private String intentionGradeType;


    /**
     * 通过ID获取详细信息
     *
     * @param: request
     * @return: ClueCustomerCollect对象
     */
    @Override
    public ClueCustomerCollect getDetailById(Long id) {
        /** 1 验证请求参数 */
        ValidateUtils.checkObjNull(id, "请求参数不能为空");
        ValidateUtils.checkLongGTZero(id, "ID不能为空或小于0");
        /** 2 处理业务 */
        ClueCustomerCollect clueCustomerCollect = clueCustomerCollectManager.getDetailById(id);
        if (EmptyUtils.isNotEmpty(clueCustomerCollect)) {
            return BeanUtil.copy(clueCustomerCollect, ClueCustomerCollect.class);
        }
        /** 3 返回结果 */
        return null;
    }

    /**
     * 单条数据插入ClueCustomerCollect
     *
     * @param request
     * @return 插入的条数
     */
    @Override
    public Long insert(ClueCustomerCollect request) {
        /** 1 验证请求参数 */
        /** 2 处理业务 */
        ClueCustomerCollectAssembler.initAddClueCustomerCollect(request);
        clueCustomerCollectManager.insert(request);
        /** 3 封装返回值 */
        return request.getId();
    }

    /**
     * 批量插入ClueCustomerCollect
     *
     * @param requests
     * @return 批量插入的条数
     */
    @Override
    public int insertBatch(List<ClueCustomerCollect> requests) {
        /** 1 验证请求参数 */
        /** 2 处理业务 */
        BasePropertyInjection.savePropertyInjection(requests);
        int count = clueCustomerCollectManager.insertBatch(requests);
        /** 3 封装返回值 */
        return count;
    }


    /**
     * 单条ClueCustomerCollect更新
     *
     * @param request
     * @return 更新的条数
     */
    @Override
    public int update(ClueCustomerCollect request) {

        /** 1 验证请求参数 */
        /** 2 处理业务 */
        BasePropertyInjection.updatePropertyInjection(request);
        int count = clueCustomerCollectManager.update(request);
        /** 3 返回对象 */
        return count;
    }

    /**
     * 通过ID删除数据
     *
     * @param request
     * @return 删除的条数
     */
    @Override
    public int delete(ClueCustomerCollect request) {
        Long id = request.getId();
        /** 1 验证请求参数 */
        ValidateUtils.checkObjNull(id, "请求参数不能为空");
        ValidateUtils.checkLongNotNullAndGTZero(id, "ID不能为空或小于0");
        /** 2 处理业务 */
        ClueCustomerCollect clueCustomerCollect = new ClueCustomerCollect();
        clueCustomerCollect.setId(id);
//		clueCustomerCollect.setDelete(DeleteEnum.DETELED.getCode());
        BasePropertyInjection.updatePropertyInjection(request);
        int count = clueCustomerCollectManager.update(clueCustomerCollect);
        /** 3 返回对象 */
        return count;
    }

    /**
     * 根据条件查询对象对象list列表
     *
     * @param request
     * @return 查询结果
     */
    @Override
    public List<ClueCustomerCollect> getListByParam(ClueCustomerCollect request) {
        /** 1 验证请求参数 */
        //可以设置排序
        /** 2 处理业务 */
        request.setDeleted(DeleteEnum.INIT.getFlag());
        request.setCorpId(SearchLocalHeader.getHeader(SCRMRequestHeaderEnum.HEADER_CORP_ACCOUNTID.getCode()));
        request.setTenantId(SearchLocalHeader.getHeader(SCRMRequestHeaderEnum.HEADER_TENANTID.getCode()));
        if (CustomerUtil.isDealer()) {
            request.setDealerId(SearchLocalHeader.getHeader(SCRMRequestHeaderEnum.HEADER_DEALER_ID.getCode()));
        }
        List<ClueCustomerCollect> queryList = clueCustomerCollectManager.getListByParam(request);
        /** 3 返回结果 */
        if (CollectionUtils.isNotEmpty(queryList)) {
            return BeanUtil.copyByList(queryList, ClueCustomerCollect.class);
        }
        return new ArrayList<>();
    }

    /**
     * 根据条件查询对象list记录
     *
     * @param request
     * @return 分页对象
     */
    @Override
    public PageResponse<ClueCustomerCollect> getPageByParam(PageRequest<ClueCustomerCollect> request) {
        /** 1 验证请求参数 */
        ValidateUtils.checkObjNull(request, "请求参数不能为空");
        //可以设置排序 query.orderByCreatedTime(true);
        /** 2 处理业务 */
        RowBounds rowBounds = new RowBounds(request.getPageNum(), request.getPageSize());


        if (EmptyUtils.isEmpty(request.getParamData())) {
            ClueCustomerCollect clueCustomerCollect = new ClueCustomerCollect();
            clueCustomerCollect.setDeleted(DeleteEnum.INIT.getFlag());
            clueCustomerCollect.setCorpId(SearchLocalHeader.getHeader(SCRMRequestHeaderEnum.HEADER_CORP_ACCOUNTID.getCode()));
            clueCustomerCollect.setTenantId(SearchLocalHeader.getHeader(SCRMRequestHeaderEnum.HEADER_TENANTID.getCode()));
            if (CustomerUtil.isDealer()) {
                clueCustomerCollect.setDealerId(SearchLocalHeader.getHeader(SCRMRequestHeaderEnum.HEADER_DEALER_ID.getCode()));
            }
            request.setParamData(clueCustomerCollect);
        } else {
            request.getParamData().setDeleted(DeleteEnum.INIT.getFlag());
            request.getParamData().setCorpId(SearchLocalHeader.getHeader(SCRMRequestHeaderEnum.HEADER_CORP_ACCOUNTID.getCode()));
            request.getParamData().setTenantId(SearchLocalHeader.getHeader(SCRMRequestHeaderEnum.HEADER_TENANTID.getCode()));
            if (CustomerUtil.isDealer()) {
                request.getParamData().setDealerId(SearchLocalHeader.getHeader(SCRMRequestHeaderEnum.HEADER_DEALER_ID.getCode()));
            }
        }


        Page<ClueCustomerCollect> queryPageList = clueCustomerCollectManager.getPageByParam(request.getParamData(), rowBounds);
        PageResponse<ClueCustomerCollect> pageResponse = new PageResponse<>();
        pageResponse.converPageResponse(pageResponse, queryPageList, request);
        pageResponse.setDataList(BeanUtil.copyByList(queryPageList.getResult(), ClueCustomerCollect.class));
        /** 3 返回结果 */
        return pageResponse;
    }

    @Override
    public PageResponse<ClueCustomerCollect> getPageByParamAll(PageRequest<QueryClueCustomerCollectAllRequest> request) {
        /** 1 验证请求参数 */
        ValidateUtils.checkObjNull(request, "请求参数不能为空");

//		request.getParamData().setDealerId(SearchLocalHeader.getHeader(SearchLocalHeader.getHeader(SCRMRequestHeaderEnum.HEADER_DEALER_ID.getCode())));


        //可以设置排序 query.orderByCreatedTime(true);
        /** 2 处理业务 */

        //1查询数据字典处理 查询所需 客户基本信息字典type列表和意向信息字典types
        List<ClueDictionaryMapped> clueDictionaryMappedList = Lists.newArrayList();
        clueDictionaryMappedList.addAll(clueDictionaryTypes.getIntentionTypes());
        clueDictionaryMappedList.addAll(clueDictionaryTypes.getCustomerBaseTypes());
        List<String> types = clueDictionaryMappedList.stream().map(ClueDictionaryMapped::getType).collect(Collectors.toList());
        types.add(DictionariesEnum.CLUE_FAIL_CODE.getType()); //战败原因字典

        QueryDictionariesRequest queryDictionariesRequest = new QueryDictionariesRequest();
        queryDictionariesRequest.setTypes(types);
        //2根据所有type 查询数据字典查询
        Response<List<DictionariesResponse>> response = tenantClient.getDictionariesListByParam(queryDictionariesRequest);
        log.info("查询数据字典产品类型返回参数:{}", JsonUtils.object2JSON(response));
        if (!Response.CODE_SUCCESS.equals(response.getCode()) || EmptyUtils.isEmpty(response.getData())) {
            throw new BusinessException(NEError.BUSINESS_ERROR, "未查询到字典信息");
        }
        //3跟进需要的字典值过滤出对应map
        //意向等级
        Map<String, String> intentionGradeMap = response.getData().stream()
                .filter(d -> DictionariesEnum.CLUE_INTENTION_GRADE.getType().equals(d.getType()))
                .collect(Collectors.toMap(DictionariesResponse::getCode, DictionariesResponse::getName));
        //战败原因
        Map<String, String> clueFailReason = response.getData().stream()
                .filter(d -> DictionariesEnum.CLUE_FAIL_CODE.getType().equals(d.getType()))
                .collect(Collectors.toMap(DictionariesResponse::getCode, DictionariesResponse::getName));

        RowBounds rowBounds = new RowBounds(request.getPageNum(), request.getPageSize());

        //4查询宽表sql


        if (EmptyUtils.isEmpty(request.getParamData())) {
            QueryClueCustomerCollectAllRequest clueCustomerCollect = new QueryClueCustomerCollectAllRequest();
            clueCustomerCollect.setDeleted(DeleteEnum.INIT.getFlag());
            clueCustomerCollect.setCorpId(SearchLocalHeader.getHeader(SCRMRequestHeaderEnum.HEADER_CORP_ACCOUNTID.getCode()));
            clueCustomerCollect.setTenantId(SearchLocalHeader.getHeader(SCRMRequestHeaderEnum.HEADER_TENANTID.getCode()));
            if (CustomerUtil.isDealer()) {
                clueCustomerCollect.setDealerId(SearchLocalHeader.getHeader(SCRMRequestHeaderEnum.HEADER_DEALER_ID.getCode()));
            }
            request.setParamData(clueCustomerCollect);
        } else {
            request.getParamData().setDeleted(DeleteEnum.INIT.getFlag());
            request.getParamData().setCorpId(SearchLocalHeader.getHeader(SCRMRequestHeaderEnum.HEADER_CORP_ACCOUNTID.getCode()));
            if (CustomerUtil.isDealer()) {
                request.getParamData().setDealerId(SearchLocalHeader.getHeader(SCRMRequestHeaderEnum.HEADER_DEALER_ID.getCode()));
            }
            request.getParamData().setTenantId(SearchLocalHeader.getHeader(SCRMRequestHeaderEnum.HEADER_TENANTID.getCode()));

        }

        QueryClueCustomerCollectAllRequest paramData = request.getParamData();
        setSearchPhoneByFindContent(paramData);
        Page<ClueCustomerCollect> queryPageList = clueCustomerCollectManager.getPageByParamAll(request.getParamData(), rowBounds);

        //操作返回对象
        queryPageList.stream().forEach(c -> {
            c.setIntentionGrade(intentionGradeMap.get(c.getIntentionGrade()));
            c.setFailReasonCodes(clueFailReason.get(c.getFailReasonCodes()));
            if (StringUtil.isNotBlank(c.getFollowContent())) {
                c.setFollowContent(FollowContentEnum.getDictionaries(Integer.parseInt(c.getFollowContent())));
            }
            if (StringUtil.isNotBlank(c.getPlanFollowContent())) {
                c.setPlanFollowContent(FollowContentEnum.getDictionaries(Integer.parseInt(c.getPlanFollowContent())));
            }
            c.setClueStatusStr(ClueStatsEnum.getDictionaries(c.getClueStatus()));
            c.setFailStatusStr(FailStatusEnum.getDictionaries(c.getFailStatus()));

            if (c.getFollowEmpId() != null && c.getFollowEmpId() != -1) {
                c.setDistributeStatus(DistributeEnum.getDictionaries(null, true));
            } else {
                c.setDistributeStatus(DistributeEnum.getDictionaries(c.getPlanFollowTime(), false));
            }

            //行为标签处理
            try {
                ObjectMapper mapper = new ObjectMapper();
                CustomerBehavior customerBehaviorAll = new CustomerBehavior();
                //经销商行为标签不为空
                if (EmptyUtils.isNotEmpty(c.getDealerCusBehavior())) {
                    //经销商行为标签转换对象
                    customerBehaviorAll = mapper.readValue(c.getDealerCusBehavior(), CustomerBehavior.class);

                }

                //如果是总部以及总部行为标签不为空
                if (!CustomerUtil.isDealer() && EmptyUtils.isNotEmpty(c.getOemCusBehavior())) {
                    //总部行为标签转换对象
                    CustomerBehavior customerBehaviorOem = mapper.readValue(c.getOemCusBehavior(), CustomerBehavior.class);
                    //总部行为标签+经销商行为标签
                    customerBehaviorAll.setFollowUpTimes(customerBehaviorAll.getFollowUpTimes() + customerBehaviorOem.getFollowUpTimes());
                    customerBehaviorAll.setVisitTimes(customerBehaviorAll.getVisitTimes() + customerBehaviorOem.getVisitTimes());
                    customerBehaviorAll.setTestDrivesTimes(customerBehaviorAll.getTestDrivesTimes() + customerBehaviorOem.getTestDrivesTimes());
                    customerBehaviorAll.setFailActivationsTimes(customerBehaviorAll.getFailActivationsTimes() + customerBehaviorOem.getFailActivationsTimes());

                }

                c.setCustomerBehavior(customerBehaviorAll);
            } catch (IOException e) {
                throw new BusinessException(NEError.BUSINESS_ERROR, "行为标签转换失败");
            }


        });

        PageResponse<ClueCustomerCollect> pageResponse = new PageResponse<>();
        pageResponse.converPageResponse(pageResponse, queryPageList, request);
        pageResponse.setDataList(BeanUtil.copyByList(queryPageList.getResult(), ClueCustomerCollect.class));
        /** 3 返回结果 */
        return pageResponse;
    }

    /**
     * 线索跟进列表头部显示
     *
     * @param: id
     * @return: ClueFollowHeadResponse
     */
    @Override
    public ClueFollowHeadResponse getHeadContent(QueryClueCustomerCollectAllRequest clueRequest) {

        //日期头部拼装
        ClueFollowHeadResponse clueFollowHeadResponse = new ClueFollowHeadResponse();
        List<ClueFollowHeadDateResponse> dateList = new ArrayList<ClueFollowHeadDateResponse>();
        List<ClueFollowHeadTypeResponse> typeList;
        List<Date> daList = CommonUtil.getSevenDate(5);
        SimpleDateFormat sd = new SimpleDateFormat("MM/dd");
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        SimpleDateFormat sdfs = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS");
        QueryClueCustomerCollectAllRequest request = new QueryClueCustomerCollectAllRequest();
        //入参copy进来
        BeanUtil.copy(clueRequest,request);
        request.setDeleted(DeleteEnum.INIT.getFlag());
        request.setCorpId(SearchLocalHeader.getHeader(SCRMRequestHeaderEnum.HEADER_CORP_ACCOUNTID.getCode()));
        request.setTenantId(SearchLocalHeader.getHeader(SCRMRequestHeaderEnum.HEADER_TENANTID.getCode()));
        if (CustomerUtil.isDealer()) {
            request.setDealerId(SearchLocalHeader.getHeader(SCRMRequestHeaderEnum.HEADER_DEALER_ID.getCode()));
        }
        setSearchPhoneByFindContent(request);

        //取拼装的最后一天 加上1天 作为 between 的上限
        request.setPlanFollowTimeUpperLimit(DateUtil.addDate(daList.get(daList.size() - 1),1));
        List<CountDateResponse> countDateResponsesount = clueCustomerCollectManager.getClueCustomerCollectDate(request);
        Integer count = 0;
        request.setDistributeStatus(-2);//第一个逾期查询
        //单独先查逾期的，逾期数后面可以优化单独拆单个接口
        count = clueCustomerCollectManager.getClueCustomerCollect(request);
        ClueFollowHeadDateResponse cfhdrOut = new ClueFollowHeadDateResponse();
        cfhdrOut.setDateStr(sd.format(daList.get(0)));
        cfhdrOut.setDateNum(count);
        cfhdrOut.setDateTime(daList.get(0));
        dateList.add(cfhdrOut);

        //拼装前端需要的数据格式
        for (int i = 1; i < daList.size(); i++) {
            ClueFollowHeadDateResponse cfhdr = new ClueFollowHeadDateResponse();
            Date cdDate =  daList.get(i);
            countDateResponsesount.stream().forEach(cd->{
                  if( sdf.format(cd.getClDate()).equals(sdf.format(cdDate))) {
                      cfhdr.setDateStr(sd.format(cdDate));
                      cfhdr.setDateNum(cd.getNum());
                      cfhdr.setDateTime(cdDate);

                  }
            });
            if(EmptyUtils.isEmpty(cfhdr.getDateNum())){
                cfhdr.setDateStr(sd.format(cdDate));
                cfhdr.setDateNum(0);
                cfhdr.setDateTime(cdDate);
            }
            dateList.add(cfhdr);
        }
        clueFollowHeadResponse.setDateList(dateList);

        //跟进内容头部拼装
        ClueCustomerCollect requests = new ClueCustomerCollect();
        requests.setPlanFollowTime(new Date());//当天时间
        //需求变更其他类型头部列表接口
//		clueFollowHeadResponse.setTypeList(getClueFollowHeadTypeResponse(requests));
        return clueFollowHeadResponse;
    }



    @Override
    public List<ClueFollowHeadTypeResponse> getClueFollowHeadTypeResponse(ClueCustomerCollect request) {

        request.setDeleted(DeleteEnum.INIT.getFlag());
        request.setCorpId(SearchLocalHeader.getHeader(SCRMRequestHeaderEnum.HEADER_CORP_ACCOUNTID.getCode()));
        request.setTenantId(SearchLocalHeader.getHeader(SCRMRequestHeaderEnum.HEADER_TENANTID.getCode()));
        if (CustomerUtil.isDealer()) {
            request.setDealerId(SearchLocalHeader.getHeader(SCRMRequestHeaderEnum.HEADER_DEALER_ID.getCode()));
        }
        List<ClueFollowHeadTypeResponse> cfhtr = clueCustomerCollectManager.getClueFollowHeadTypeResponse(request);
        ClueFollowHeadTypeResponse cfht = new ClueFollowHeadTypeResponse();

        AtomicInteger an = new AtomicInteger();

        //汇总总数
        cfht.setHeadStr("all");
        cfht.setHeadValue("全部");
        cfhtr.stream().forEach(c -> {
            if (StringUtil.isNotBlank(c.getHeadStr())) {
                //显示跟进内容
                if (c.getHeadStr().equals(FollowContentEnum.PRODUCT_INTRO.getCode().toString())) {
                    c.setHeadValue(FollowContentEnum.PRODUCT_INTRO.getName());
                }
                if (c.getHeadStr().equals(FollowContentEnum.CHECKIN.getCode().toString())) {
                    c.setHeadValue(FollowContentEnum.CHECKIN.getName());
                }
                if (c.getHeadStr().equals(FollowContentEnum.DRIVE_TEST.getCode().toString())) {
                    c.setHeadValue(FollowContentEnum.DRIVE_TEST.getName());
                }
                if (c.getHeadStr().equals(FollowContentEnum.ORDER.getCode().toString())) {
                    c.setHeadValue(FollowContentEnum.ORDER.getName());
                }
                if (c.getHeadStr().equals(FollowContentEnum.DELIVERY.getCode().toString())) {
                    c.setHeadValue(FollowContentEnum.DELIVERY.getName());
                }

                an.addAndGet(c.getHeadNum());
            }

        });
        cfht.setHeadNum(an.get());
        return cfhtr;
    }

    @Override
    public List<ClueFollowHeadTypeResponse> getClueStatusHeadTypeResponse(QueryClueCustomerCollectAllRequest request) {
        request.setDeleted(DeleteEnum.INIT.getFlag());
        request.setCorpId(SearchLocalHeader.getHeader(SCRMRequestHeaderEnum.HEADER_CORP_ACCOUNTID.getCode()));
        request.setTenantId(SearchLocalHeader.getHeader(SCRMRequestHeaderEnum.HEADER_TENANTID.getCode()));
        if (CustomerUtil.isDealer()) {
            request.setDealerId(SearchLocalHeader.getHeader(SCRMRequestHeaderEnum.HEADER_DEALER_ID.getCode()));
        }
        setSearchPhoneByFindContent(request);
        return clueCustomerCollectManager.getClueStatusHeadTypeResponse(request);
    }

    @Override
    public int updateByIds(ClueCustomerCollect request) {
        /** 1 验证请求参数 */
        ValidateUtils.checkObjNull(request.getIds(), "IDS不能为空");
        /** 2 处理业务 */
        request = ClueCustomerCollectAssembler.initUpdateClueCustomerCollect(request);
        int count = clueCustomerCollectManager.updateByIds(request);
        /** 3 返回对象 */
        return count;
    }

    /**
     * 头部部战败审批统计
     *
     * @param request
     * @return 头部部战败审批统计
     */
    @Override
    public List<ClueFollowHeadTypeResponse> getClueFailFollowHeadTypeResponse(QueryClueCustomerCollectAllRequest request) {
        request.setDeleted(DeleteEnum.INIT.getFlag());
        request.setCorpId(SearchLocalHeader.getHeader(SCRMRequestHeaderEnum.HEADER_CORP_ACCOUNTID.getCode()));
        request.setTenantId(SearchLocalHeader.getHeader(SCRMRequestHeaderEnum.HEADER_TENANTID.getCode()));
        if (CustomerUtil.isDealer()) {
            request.setDealerId(SearchLocalHeader.getHeader(SCRMRequestHeaderEnum.HEADER_DEALER_ID.getCode()));
        }
        setSearchPhoneByFindContent(request);
        List<ClueFollowHeadTypeResponse> cfhtr = clueCustomerCollectManager.getClueFailFollowHeadTypeResponse(request);
        //全部
        ClueFollowHeadTypeResponse cfht = new ClueFollowHeadTypeResponse();
        //已审批
        //ClueFollowHeadTypeResponse isApproval = new ClueFollowHeadTypeResponse();
        //全部统计
        AtomicInteger an = new AtomicInteger();
        //已审批统计
        AtomicInteger isan = new AtomicInteger();
        //汇总总数

        cfht.setHeadValue("全部");
        cfht.setHeadStr("all");
        //isApproval.setHeadValue("已审批");
        //已审批先查询已同意和已拒绝的
        //isApproval.setHeadStr(FailStatusEnum.AGREE.getCode().toString() + "," + FailStatusEnum.REFUSE.getCode().toString());

        cfhtr.stream().forEach(c -> {
            //显示跟进内容
            if (c.getHeadStr().equals(FailStatusEnum.APPROVAL_PENDING.getCode().toString())) {
                c.setHeadValue(FailStatusEnum.APPROVAL_PENDING.getName());
            }
            if (c.getHeadStr().equals(FailStatusEnum.AGREE.getCode().toString())) {
                c.setHeadValue(FailStatusEnum.AGREE.getName());
                //isan.addAndGet(c.getHeadNum()); //已审批统计
            }
            if (c.getHeadStr().equals(FailStatusEnum.REFUSE.getCode().toString())) {
                c.setHeadValue(FailStatusEnum.REFUSE.getName());
                //isan.addAndGet(c.getHeadNum()); //已审批统计
            }
            if (c.getHeadStr().equals(FailStatusEnum.ACTIVATE.getCode().toString())) {
                c.setHeadValue(FailStatusEnum.ACTIVATE.getName());
//				isan.addAndGet(c.getHeadNum()); //已审批统计
            }

            an.addAndGet(c.getHeadNum());

        });

        cfht.setHeadNum(an.get());
//        isApproval.setHeadNum(isan.get());
//        cfhtr.add(isApproval);
        return cfhtr;


    }

    private void setSearchPhoneByFindContent(QueryClueCustomerCollectAllRequest request) {
        if (StringUtils.isNotBlank(request.getFindContent())) {
            request.setPhoneForFindContent(request.getFindContent());
        }
        if (StringUtils.isNotBlank(request.getFindCustomerKey())) {
            request.setPhoneForFindContent(request.getFindCustomerKey());
        }
    }

    @Override
    public List<ClueFollowHeadTypeResponse> getClueDistributeResponse(QueryClueCustomerCollectAllRequest request) {
        List<ClueFollowHeadTypeResponse> cfhtr = new ArrayList<ClueFollowHeadTypeResponse>();

        request.setDeleted(DeleteEnum.INIT.getFlag());
        request.setCorpId(SearchLocalHeader.getHeader(SCRMRequestHeaderEnum.HEADER_CORP_ACCOUNTID.getCode()));
        request.setTenantId(SearchLocalHeader.getHeader(SCRMRequestHeaderEnum.HEADER_TENANTID.getCode()));
        if (CustomerUtil.isDealer()) {
            request.setDealerId(SearchLocalHeader.getHeader(SCRMRequestHeaderEnum.HEADER_DEALER_ID.getCode()));
        }
        setSearchPhoneByFindContent(request);
        ClueDistributeResponse clueDistributeResponse = clueCustomerCollectManager.getClueDistributeResponse(request);
        ClueFollowHeadTypeResponse cfhtAll = new ClueFollowHeadTypeResponse();
        cfhtAll.setHeadStr("all");
        cfhtAll.setHeadValue("全部");
        cfhtAll.setHeadNum(clueDistributeResponse.getDistributeNum());
        cfhtr.add(cfhtAll);
        Arrays.stream(DistributeEnum.values()).forEach(
                d -> {
                    ClueFollowHeadTypeResponse cfht = new ClueFollowHeadTypeResponse();
                    cfht.setHeadValue(d.getName());
                    cfht.setHeadStr(d.getCode().toString());
                    if (-1 == d.getCode()) {
                        cfht.setHeadNum(clueDistributeResponse.getExpiryOutNum());
                    }
                    if (0 == d.getCode()) {
                        cfht.setHeadNum(clueDistributeResponse.getDistributePendingNum());
                    }
                    if (1 == d.getCode()) {
                        cfht.setHeadNum(clueDistributeResponse.getDistributeNum() - clueDistributeResponse.getDistributePendingNum());
                    }
                    cfhtr.add(cfht);
                }
        );

        return cfhtr;
    }

    @Override
    public ClueCustomerCollect getOneByParam(ClueCustomerCollect collectRequest) {
        ValidateUtils.checkObjNull(collectRequest, "请求参数错误");
        collectRequest.setDeleted(DeleteEnum.INIT.getFlag());
        collectRequest.setCorpId(SearchLocalHeader.getHeader(SCRMRequestHeaderEnum.HEADER_CORP_ACCOUNTID.getCode()));
        collectRequest.setTenantId(SearchLocalHeader.getHeader(SCRMRequestHeaderEnum.HEADER_TENANTID.getCode()));
        if (CustomerUtil.isDealer()) {
            collectRequest.setDealerId(SearchLocalHeader.getHeader(SCRMRequestHeaderEnum.HEADER_DEALER_ID.getCode()));
        }
        return clueCustomerCollectManager.getOneByParam(collectRequest);
    }

    @Override
    public Boolean updateClueCustomerCollect(UpdateClueCustomerRequest request) {
        ValidateUtils.checkObjNull(request, "宽表更新参数为null");

        //客户基本信息
        if (EmptyUtils.isNotEmpty(request.getUpdateCustomer())) {
            Long cusId = EmptyUtils.isEmpty(request.getUpdateCustomer()) ? request.getUpdateClueIntention().getCusId() : request.getUpdateCustomer().getId();
            ValidateUtils.checkLongGTZero(cusId, "客户ID不可以为null");

            ClueCustomerCollect queryClueCustomerCollect = new ClueCustomerCollect();
            queryClueCustomerCollect.setCusId(cusId);
            queryClueCustomerCollect.setDeleted(DeleteEnum.INIT.getFlag());
            List<ClueCustomerCollect> existClueCustomers = clueCustomerCollectManager.getListByParam(queryClueCustomerCollect);
            if (EmptyUtils.isEmpty(existClueCustomers)) {
                throw new BusinessException(NEError.BUSINESS_ERROR, "客户信息更新-线索宽表信息不存在");
            }
            List<Long> clueCollectIds = existClueCustomers.stream().map(ClueCustomerCollect::getId).collect(Collectors.toList());
            ClueCustomerCollect clueCustomerCollect = ClueCustomerCollectAssembler.initUpdateByCustomerInfo(request.getUpdateCustomer());
            clueCustomerCollect.setIds(clueCollectIds);
            int result = clueCustomerCollectManager.updateByIds(clueCustomerCollect);
            if (result <= 0) {
                throw new BusinessException(NEError.BUSINESS_ERROR, "客户信息-更新线索宽表信息失败");
            }
        }

        //线索意向信息
        if (EmptyUtils.isNotEmpty(request.getUpdateClueIntention())) {
            Long clueId = EmptyUtils.isEmpty(request.getUpdateCustomer()) ? request.getUpdateClueIntention().getClueId() : request.getUpdateCustomer().getClueId();
            ValidateUtils.checkLongGTZero(clueId, "线索ID为null");
            ClueCustomerCollect queryClueCustomerCollect = new ClueCustomerCollect();
            queryClueCustomerCollect.setClueId(clueId);
            queryClueCustomerCollect.setDeleted(DeleteEnum.INIT.getFlag());
            ClueCustomerCollect exist = clueCustomerCollectManager.getOneByParam(queryClueCustomerCollect);
            ValidateUtils.checkObjNull(exist, "线索宽表信息不存在， clueId=" + clueId);

            ClueCustomerCollect clueCustomerCollect = new ClueCustomerCollect();
            UpdateClueIntentionRequest clueIntentionRequest = request.getUpdateClueIntention();
            clueCustomerCollect.setIntentionGrade(clueIntentionRequest.getIntentionGrade());
            clueCustomerCollect.setSeriesId(clueIntentionRequest.getSeriesId());
            clueCustomerCollect.setModelId(clueIntentionRequest.getModelId());
            clueCustomerCollect.setModelYearId(clueIntentionRequest.getModelYearId());
            clueCustomerCollect.setConfigId(clueIntentionRequest.getConfigId());
            clueCustomerCollect.setBrandId(clueIntentionRequest.getBrandId());

            clueCustomerCollect.setId(exist.getId());
            clueCustomerCollect = ClueCustomerCollectAssembler.initUpdateClueCustomerCollect(clueCustomerCollect);
            int updateResult = clueCustomerCollectManager.update(clueCustomerCollect);
            if (updateResult <= 0) {
                throw new BusinessException(NEError.BUSINESS_ERROR, "更新线索宽表信息失败");
            }
        }
        return true;
    }

    @Override
    public Boolean updateByFollowInfo(AddClueCustomerFollowRequest request) {
        Long clueId = EmptyUtils.isEmpty(request.getAddCustomerFollowPlan()) ? request.getAddCustomerFollowRecord().getClueId() : request.getAddCustomerFollowPlan().getClueId();
        ValidateUtils.checkLongGTZero(clueId, "线索ID不存在");

        ClueCustomerCollect queryClueCollect = new ClueCustomerCollect();
        queryClueCollect.setClueId(clueId);
        queryClueCollect.setDeleted(DeleteEnum.INIT.getFlag());
        ClueCustomerCollect exist = clueCustomerCollectManager.getOneByParam(queryClueCollect);
        if (EmptyUtils.isEmpty(exist)) {
            throw new BusinessException(NEError.BUSINESS_ERROR, "更新线索集合数据信息不存在");
        }

        ClueCustomerCollect clueCustomerCollect = new ClueCustomerCollect();
        //跟进计划
        if (EmptyUtils.isNotEmpty(request.getAddCustomerFollowPlan())) {
            AddCustomerFollowPlanRequest followPlan = request.getAddCustomerFollowPlan();
            clueCustomerCollect.setPlanFollowContent(followPlan.getPlanFollowContent());
            clueCustomerCollect.setPlanFollowTime(followPlan.getPlanFollowTime());
            clueCustomerCollect.setPlanFollowTimeCode(followPlan.getPlanFollowTimeCode());
            clueCustomerCollect.setPlanFollowId(followPlan.getId());
            clueCustomerCollect.setClueId(followPlan.getClueId());
            ClueCustomerCollectAssembler.initClueCustomerCollect(clueCustomerCollect);
        }

        //跟进记录
        if (EmptyUtils.isNotEmpty(request.getAddCustomerFollowRecord())) {
            clueCustomerCollect = ClueCustomerCollectAssembler.initUpdateByFollowInfo(clueCustomerCollect, request.getAddCustomerFollowRecord(), exist);
            if (StringUtils.equals(request.getAddCustomerFollowRecord().getFollowContent(), FollowContentEnum.ORDER.getCode().toString())) {
                //如果下訂的话，意向等级强制为O
                List<DictionariesResponse> dictionariesResponseList = dictionaryService.listDictionary(intentionGradeType);
                DictionariesResponse dictionariesResponse = dictionariesResponseList.stream().filter(d -> d.getName().startsWith("O")).findFirst().orElse(null);
                if (dictionariesResponse != null) {
                    clueCustomerCollect.setIntentionGrade(dictionariesResponse.getCode());
                }
            }
            long followNum = EmptyUtils.isEmpty(exist.getFollowNum()) ? 0L : exist.getFollowNum();
            clueCustomerCollect.setFollowNum(followNum + 1L);
            clueCustomerCollect.setUpdatedTime(exist.getUpdatedTime());
        }

        clueCustomerCollect.setId(exist.getId());
        int collectResult = clueCustomerCollectManager.updateByIdAndUpdateTime(clueCustomerCollect);
        if (collectResult <= 0) {
            throw new BusinessException(NEError.BUSINESS_ERROR, "更新线索集合信息失败");
        }
        return true;
    }

    /**
     * 根据线索id修改搜索宽表信息
     * 目前用于战败申请时修改宽表
     *
     * @param request
     * @return
     */
    @Override
    public int updateByClueId(ClueCustomerCollect request) {
        request = ClueCustomerCollectAssembler.initUpdateClueCustomerCollect(request);
        return clueCustomerCollectManager.updateByClueId(request);
    }


    /**
     * 单条数据查询统计 ClueCustomerCollect
     *
     * @param request
     * @return 插入的条数
     */
    @Override
    public int getClueCustomerCollect(QueryClueCustomerCollectAllRequest request) {
        request.setDeleted(DeleteEnum.INIT.getFlag());
        request.setCorpId(SearchLocalHeader.getHeader(SCRMRequestHeaderEnum.HEADER_CORP_ACCOUNTID.getCode()));
        request.setTenantId(SearchLocalHeader.getHeader(SCRMRequestHeaderEnum.HEADER_TENANTID.getCode()));
        if (CustomerUtil.isDealer()) {
            request.setDealerId(SearchLocalHeader.getHeader(SCRMRequestHeaderEnum.HEADER_DEALER_ID.getCode()));
        }
        setSearchPhoneByFindContent(request);
        return clueCustomerCollectManager.getClueCustomerCollect(request);
    }

    @Override
    public PageResponse<ClueExpirePesponse> getOemOrDealerClueExpireList(PageRequest<ClueExpireRequest> request) {


        /** 1 验证请求参数 */
        ValidateUtils.checkObjNull(request, "请求参数不能为空");
        //可以设置排序 query.orderByCreatedTime(true);
        /** 2 处理业务 */
        String dealerId = SearchLocalHeader.getHeader(SCRMRequestHeaderEnum.HEADER_DEALER_ID.getCode());

        RowBounds rowBounds = new RowBounds(request.getPageNum(), request.getPageSize());


        if (EmptyUtils.isEmpty(request.getParamData())) {
            ClueExpireRequest clueExpireRequest = new ClueExpireRequest();
            clueExpireRequest.setDeleted(DeleteEnum.INIT.getFlag());
            clueExpireRequest.setCorpId(SearchLocalHeader.getHeader(SCRMRequestHeaderEnum.HEADER_CORP_ACCOUNTID.getCode()));
            clueExpireRequest.setTenantId(SearchLocalHeader.getHeader(SCRMRequestHeaderEnum.HEADER_TENANTID.getCode()));
            if (CustomerUtil.isDealer()) {
                clueExpireRequest.setDealerId(SearchLocalHeader.getHeader(SCRMRequestHeaderEnum.HEADER_DEALER_ID.getCode()));
            }
            request.setParamData(clueExpireRequest);
        } else {
            request.getParamData().setDeleted(DeleteEnum.INIT.getFlag());
            request.getParamData().setCorpId(SearchLocalHeader.getHeader(SCRMRequestHeaderEnum.HEADER_CORP_ACCOUNTID.getCode()));
            request.getParamData().setTenantId(SearchLocalHeader.getHeader(SCRMRequestHeaderEnum.HEADER_TENANTID.getCode()));
            if (CustomerUtil.isDealer()) {
                request.getParamData().setDealerId(SearchLocalHeader.getHeader(SCRMRequestHeaderEnum.HEADER_DEALER_ID.getCode()));
            }
        }

        ClueExpireRequest paramData = request.getParamData();
        setSearchPhoneByFindContent(paramData);

        Page<ClueExpirePesponse> queryPageList = new Page<ClueExpirePesponse>();
        if (!CustomerUtil.isDealer()) {
            //总部跟进
            queryPageList = clueCustomerCollectManager.getOemClueExpireList(request.getParamData(), rowBounds);
        } else {
            //经销商跟进
            request.getParamData().setDealerId(dealerId);
            queryPageList = clueCustomerCollectManager.getDealerClueExpireList(request.getParamData(), rowBounds);

        }


        PageResponse<ClueExpirePesponse> pageResponse = new PageResponse<ClueExpirePesponse>();
        pageResponse.converPageResponse(pageResponse, queryPageList, request);
        pageResponse.setDataList(BeanUtil.copyByList(queryPageList.getResult(), ClueExpirePesponse.class));
        /** 3 返回结果 */
        return pageResponse;
    }

//    @Override
//    public PageResponse<ClueExpirePesponse> getOemOrDealerClueExpireList(PageRequest<ClueExpireRequest> request,String num) {
//        /** 1 验证请求参数 */
//        ValidateUtils.checkObjNull(request, "请求参数不能为空");
//        //可以设置排序 query.orderByCreatedTime(true);
//        /** 2 处理业务 */
//        String dealerId = SearchLocalHeader.getHeader(SCRMRequestHeaderEnum.HEADER_DEALER_ID.getCode());
//
//        RowBounds rowBounds = new RowBounds(request.getPageNum(), request.getPageSize());
//
//
//        if (EmptyUtils.isEmpty(request.getParamData())) {
//            ClueExpireRequest clueExpireRequest = new ClueExpireRequest();
//            clueExpireRequest.setDeleted(DeleteEnum.INIT.getFlag());
//            clueExpireRequest.setCorpId(SearchLocalHeader.getHeader(SCRMRequestHeaderEnum.HEADER_CORP_ACCOUNTID.getCode()));
//            clueExpireRequest.setTenantId(SearchLocalHeader.getHeader(SCRMRequestHeaderEnum.HEADER_TENANTID.getCode()));
//            if (CustomerUtil.isDealer()) {
//                clueExpireRequest.setDealerId(SearchLocalHeader.getHeader(SCRMRequestHeaderEnum.HEADER_DEALER_ID.getCode()));
//            }
//            request.setParamData(clueExpireRequest);
//        } else {
//            request.getParamData().setDeleted(DeleteEnum.INIT.getFlag());
//            request.getParamData().setCorpId(SearchLocalHeader.getHeader(SCRMRequestHeaderEnum.HEADER_CORP_ACCOUNTID.getCode()));
//            request.getParamData().setTenantId(SearchLocalHeader.getHeader(SCRMRequestHeaderEnum.HEADER_TENANTID.getCode()));
//            if (CustomerUtil.isDealer()) {
//                request.getParamData().setDealerId(SearchLocalHeader.getHeader(SCRMRequestHeaderEnum.HEADER_DEALER_ID.getCode()));
//            }
//        }
//
//        Page<ClueExpirePesponse> queryPageList = new Page<ClueExpirePesponse>();
//        if (!CustomerUtil.isDealer()) {
//            //经销商跟进
//            request.getParamData().setDealerId(dealerId);
//            queryPageList = clueCustomerCollectManager.getDealerClueExpireList(request.getParamData(), rowBounds);
//
//        } else {
//
//            //先查询经销商跟进记录
//            PageRequest<DealerCustomerFollowRecord> dealerRecordPageRequest =  DealerCustomerFollowRecordAssembler.transformVOToPOPage(request, DealerCustomerFollowRecord.class);
//            List<Integer> expireStatusList = new ArrayList<Integer>();
//            expireStatusList.add(ExpireStatusEnum.EXPIRY_OUT.getCode());
//            expireStatusList.add(ExpireStatusEnum.EXPIRY_OUT_FIRST.getCode());
//            dealerRecordPageRequest.getParamData().setExpireStatusList(expireStatusList);
//            dealerRecordPageRequest.getParamData().setStatus(FollowRecordStatusEnum.FOLLOW_UP.getCode());
//            //经销商跟进
//            dealerRecordPageRequest.getParamData().setDealerId(dealerId);
//            PageResponse<DealerCustomerFollowRecord>  redcf = dealerCustomerFollowRecordService.getPageByParam(dealerRecordPageRequest);
//
//            List<Long> clueId = redcf.getDataList().stream().map(DealerCustomerFollowRecord::getClueId).collect(Collectors.toList());
//            List<Long> cusId = redcf.getDataList().stream().map(DealerCustomerFollowRecord::getCusId).collect(Collectors.toList());
//            List<Long> followPlanId = redcf.getDataList().stream().map(DealerCustomerFollowRecord::getFollowPlanId).collect(Collectors.toList());
//
//
//            PageResponse<ClueExpirePesponse> cepList =  DealerCustomerFollowRecordAssembler.transformPOToResponseVoPage(redcf,ClueExpirePesponse.class);
//
//
//            //copyList到对应返回list
//
//
//            if(EmptyUtils.isNotEmpty(clueId)){
//                //跟进历史表有对应逾期数据，查询线索关联表
//                Clue clue = new Clue();
//                clue.setIds(clueId);
//                List<Clue> clueList =  clueService.getListByParam(clue);
//                //跟进历史表有对应逾期数据，查询顾客关联表
//                QueryCustomerRequest queryCustomerRequest = new QueryCustomerRequest();
//                queryCustomerRequest.setIds(cusId);
//                List<CustomerResponse> crlist = dealerCustomerService.getListByParam(queryCustomerRequest);
//                //跟进历史表有对应逾期数据，查询总部计划关联表
//                QueryCustomerFollowPlanRequest queryCustomerFollowPlanRequest = new QueryCustomerFollowPlanRequest();
//                queryCustomerFollowPlanRequest.setIds(followPlanId);
//                List<DealerCustomerFollowPlan> dcfList =  dealerCustomerFollowPlanService.getListByParam(queryCustomerFollowPlanRequest);
//                cepList.getDataList().stream().forEach(ce -> {
//                    clueList.stream().filter(c-> Objects.equals(c.getId(),ce.getClueId())).forEach(c->{
//                        ce.setDistributeTime(c.getDistributeTime());
//                    });
//                    crlist.stream().filter(r-> Objects.equals(r.getId(),ce.getCusId())).forEach(r->{
//                        ce.setAvatar(r.getAvatar());
//                        ce.setName(r.getName());
//                        ce.setPhone(r.getPhone());
//                        ce.setQwName(r.getQwName());
//                        ce.setCustomerBaseId(r.getCustomerBaseId());
//                        ce.setExternalUserid(r.getExternalUserid());
//                    });
//                    dcfList.stream().filter(d -> Objects.equals(d.getId(),ce.getFollowPlanId())).forEach(d->{
//                        ce.setPlanFollowTime(d.getPlanFollowTime());
//
//                    });
//
//                });
//
//
//
//            }
//
//            /** 3 返回结果 */
//            return cepList;
//
//        }
//
//        PageResponse<ClueExpirePesponse> pageResponse = new PageResponse<ClueExpirePesponse>();
//        pageResponse.converPageResponse(pageResponse, queryPageList, request);
//        pageResponse.setDataList(BeanUtil.copyByList(queryPageList.getResult(), ClueExpirePesponse.class));
//        /** 3 返回结果 */
//        return pageResponse;
//    }


    @Override
    public int updateByCusIdsAndDealerId(ClueCustomerCollect request) {
        return clueCustomerCollectManager.updateByCusIdsAndDealerId(request);
    }

    /**
     * 根据条件查看显示未分配的数量
     * add by zly
     *
     * @param clueIntentionGradeDataRequest
     * @return
     */
    @Override
    public Integer getDistributeCount(ClueIntentionGradeDataRequest clueIntentionGradeDataRequest) {
        return clueCustomerCollectManager.getDistributeCount(clueIntentionGradeDataRequest);
    }

    @Override
    public int updateByIdAndUpdateTime(ClueCustomerCollect clueCustomerCollect) {
        return clueCustomerCollectManager.updateByIdAndUpdateTime(clueCustomerCollect);
    }

    private void setSearchPhoneByFindContent(ClueExpireRequest request) {
        if (StringUtils.isNotBlank(request.getFindContent())) {
            request.setPhoneForFindContent(request.getFindContent());
        }
    }
}
